<template>
  <div class="week_report">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>本周工作简报</span>
        </div>
      </template>
      <el-button type="success" class='btn' @click="download">导出本周简报</el-button>
      <el-button type="primary" class='btn' @click="add">新增</el-button>

      
      <el-table :data="tableData" border style="width: 100%; margin-top: 20px" :row-class-name="tableRowClassName">
        <el-table-column prop="progress" label="进度" width="150">
          <template #default="scope">
            <el-button round v-if="scope.row.progress !== '100'" @click="showDialog(scope.row.id)">进行中</el-button>
            <el-button round v-if="scope.row.progress === '100'" type="danger">已完成</el-button>
          </template>
        </el-table-column>
        <el-table-column prop="product_name" label="项目名称" />
        <el-table-column prop="member" label="参与人员">
          <template #default="scope">
            <el-tag class="ml-2" v-for="name in scope.row.member.split(',')" :key="name" @click="nameClick(name)">{{ name
            }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="department_name" label="部门" />
        <el-table-column prop="work_date" label="开始日期" >
          <template #default="scope">
            {{ formatter(scope.row.work_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="deadline_date" label="截止日期" >
          <template #default="scope">
            {{ formatter(scope.row.deadline_date) }}
          </template>
        </el-table-column>
        <el-table-column prop="notes" label="备注">
          <template #default="scope">
                <span v-html="formatRemark(scope.row.notes)"></span>
              </template>
        </el-table-column>

        <el-table-column label="操作" width="160">
          <template #default="scope">
            <el-button size="small" @click="editOrder(scope.row.id)">编辑</el-button>
            <el-button type="danger" size="small" @click="deleteOrder(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog v-model="dialogTableVisible" title="选择文件数量" width="304">
        <el-form ref="form" :model="formData" class="el-group-complete">
            <el-form-item label="海报设计：" label-width="93px">
              <el-input-number v-model="formData.haibao" :min="0" style="width: 150px" />
            </el-form-item>

            <el-form-item label="长图设计：" label-width="93px">
              <el-input-number v-model="formData.changtu" :min="0" style="width: 150px" />
            </el-form-item>

            <el-form-item label="H5设计：" label-width="93px">
              <el-input-number v-model="formData.h5" :min="0" style="width: 150px" />
            </el-form-item>

            <el-form-item label="视频制作：" label-width="93px">
              <el-input-number v-model="formData.shipin" :min="0" style="width: 150px" />
            </el-form-item>
            <el-form-item label="资源图：" label-width="93px">
              <el-input-number v-model="formData.ziyuan" :min="0" style="width: 150px" />
            </el-form-item>

            <el-form-item label="插画：" label-width="93px">
              <el-input-number v-model="formData.chahua" :min="0" style="width: 150px" />
            </el-form-item>

            <el-form-item label="动画：" label-width="93px">
              <el-input-number v-model="formData.donghua" :min="0" style="width: 150px" />
            </el-form-item>

            <el-form-item label="PPT杂志：" label-width="93px">
              <el-input-number v-model="formData.ppt" :min="0" style="width: 150px" />
            </el-form-item>

            <el-form-item label="物料：" label-width="93px">
              <el-input-number v-model="formData.wuliao" :min="0" style="width: 150px" />
            </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer" style="text-align: center;margin-top:-20px;margin-bottom:20px">
            <el-button type="primary" @click="goComplete()">
              确定
            </el-button>
            <el-button @click="cancel()">取消</el-button>
          </div>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import workApi from '../../api/work'
import { onMounted, reactive, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from 'vue-router'
const router = useRouter()
const dialogTableVisible = ref(false)
const colors = [
  { color: '#f56c6c', percentage: 20 },
  { color: '#e6a23c', percentage: 40 },
  { color: '#5cb87a', percentage: 60 },
  { color: '#1989fa', percentage: 80 },
  { color: 'green', percentage: 100 },
]
// Dom 挂载之后
onMounted(() => {
  getRecentWorks()
})
// 数据
const tableData = ref([])

const username = sessionStorage.getItem('username')

// form
const formData = reactive({
  id: '',
  haibao: '',
  changtu: '',
  h5: '',
  shipin: '',
  ziyuan: '',
  chahua: '',
  donghua: '',
  ppt: '',
  wuliao: '',
  work_date:'',
  deadline_date:'',
  username: username
})
// 获取最近工作列表
const getRecentWorks = async () => {
  const res = await workApi.getRecentWorks()
  console.log(res.data)
  if (res.status == 200) {
    tableData.value = res.data

    // 将已完成的数据放到最后面
    tableData.value = tableData.value.sort((a, b) => {
      return a.progress === '100' ? 1 : b.progress === '100' ? -1 : 0
    })

  }
}

const tableRowClassName = (row, rowIndex) => {
  if (row.row.progress === '100') {
    return 'warning-row'
  }
  return ''
}

const add = async () => {
  router.push({
    path: '/week_report/add',
  })
}

const editOrder = async (id) => {
  router.push({
    path: '/week_report/add',
    query: { id: id },
  })
}

const customSortMethod = (a, b) => {
  const progressA = parseInt(a.progress)
  const progressB = parseInt(b.progress)

  // 正常排序
  return progressA - progressB
}

// 删除项目
const deleteOrder = (id) => {
  ElMessageBox.confirm('确定要删除该项目吗?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const username = sessionStorage.getItem('username')
      const res = await workApi.delOrder({ id: id, username: username })
      if (res.data.success) {
        ElMessage.success('删除成功')
        getRecentWorks()
      } else {
        ElMessage.error('删除失败')
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

const nameClick = async (name) => {
  router.push({
    path: '/member_report',
  });
}

const download = async () => {
  const lastSaturday = getLastSaturday();
  const nextSaturday = getNextSaturday();
  const lastSaturdayFormatted = formatDate(lastSaturday);
  const nextSaturdayFormatted = formatDate(nextSaturday);

  const data = tableData.value.map((item, index) => {
    let result = ''
    if (item.progress === '100') {
      result = `${index + 1}. ${item.department_name}（已完成）：${item.product_name}`;
    } else {
      result = `${index + 1}. ${item.department_name}：${item.product_name}`;
    }
    if (item.notes) {
      result += `，${item.notes}`
    }
    return result;
  }).join('\r\n');

  // 创建 Blob 对象，确保 MIME 类型为 text/plain
  const blob = new Blob([data], { type: 'text/plain;charset=utf-8' });

  // 创建下载链接并触发下载
  const link = document.createElement('a');
  link.href = URL.createObjectURL(blob);
  link.download = `${lastSaturdayFormatted}__${nextSaturdayFormatted}_简报.txt`;
  link.click();

  // 释放 URL 对象
  URL.revokeObjectURL(link.href);
}

const getLastSaturday = () => {
  const today = new Date();
  const dayOfWeek = today.getDay();
  const lastSaturday = new Date(today);
  lastSaturday.setDate(today.getDate() - dayOfWeek - 1);
  if (dayOfWeek === 0) {
    lastSaturday.setDate(lastSaturday.getDate() - 7);
  }
  return lastSaturday;
};

const getNextSaturday = () => {
  const today = new Date();
  const dayOfWeek = today.getDay();
  const diff = 6 - dayOfWeek;
  const nextSaturday = new Date(today);
  nextSaturday.setDate(today.getDate() + diff);
  return nextSaturday;
};

const formatDate = (date) => {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};
const showDialog = (id) => {
  dialogTableVisible.value = true
  formData.id = id
}
const goComplete = async () => {
  ElMessageBox.confirm('确定完成吗?', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      const res = await workApi.goComplete(formData)
      if (res.data.success) {
        ElMessage.success('更新成功')
        cancel()
        getRecentWorks()
      } else {
        ElMessage.error('更新失败')
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

const cancel = () => {
  dialogTableVisible.value = false
  Object.assign(formData, {
    id: '',
    haibao: '',
    changtu: '',
    h5: '',
    shipin: '',
    ziyuan: '',
    chahua: '',
    donghua: '',
    ppt: '',
    wuliao: '',
    username: username
  });
}

const formatRemark = (remark) => {
  if (!remark) return '';

  // 正则表达式匹配 URL
  const urlPattern = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gi;

  // 将 URL 替换为超链接并替换换行符为 <br>
  return remark
    .replace(urlPattern, (url) => `<a href="${url}" target="_blank">${url}</a>`)
    .replace(/\n/g, '<br>');
};

const formatter = (date) =>{
  if (!date) return '';
      let dateObj;
      if (typeof date === 'string' || typeof date === 'number') {
        dateObj = new Date(date);
      } else if (date instanceof Date) {
        dateObj = date;
      } else {
        return '';
      }

      if (isNaN(dateObj)) {
        return '';
      }

      return dateObj.toLocaleDateString('zh-CN', { timeZone: 'Asia/Shanghai' });
}

</script>

<style>
.week_report .btn {
  float: right;
  margin-bottom: 20px;
  margin-right: 10px
}

.week_report .el-table .cell {
  text-align: center;
  line-height: 100%;
}

.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}

.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}

.el-tag.ml-2 {
  margin: 4px;
  cursor: pointer;
}

.el-table thead tr {
  font-size: 17px;
}

.el-progress-circle {
  width: 50px !important;
  height: 50px !important;
}

.el-progress__text span {
  font-size: 13px;
}

.el-group-complete .files {
  margin: 10px 40px;
  padding: 30px;
  border-radius: 20px;
  background: rgb(255 255 255);
  box-shadow: rgba(0, 0, 0, 0.45) 0px 5px 40px 0px;
  max-width: 600px;
  width: 300px;
}

.right-aligned-label .el-form-item__label {
  text-align: right;
  display: block;
  width: auto;
  /* Ensure label width adapts to its content */
}
</style>
